from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from starlette.responses import JSONResponse
from config.schemas import BaseResponse

from config.cors import setup_cors
from modules.akshare.dongcai_api import router

import glob
import os
from importlib import import_module
from config.database import Base, engine

app = FastAPI(
    title="欢迎访问 API 在线文档",
    description="stock 的接口文档",
    redoc_url=None,
)

Base.metadata.create_all(bind=engine)


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    """自定义参数验证错误响应"""
    return JSONResponse(
        status_code=422,
        content=BaseResponse.error(
            code=422,
            msg="参数验证失败",
            data=exc.errors()
        ).dict()
    )


# 初始化配置
setup_cors(app)

# app.include_router(router, prefix="")

# 自动导入路由
modules_path = os.path.join(os.path.dirname(__file__), "modules")
for module_path in glob.glob(f"{modules_path}/**/*.py", recursive=True):
    if not module_path.endswith("__init__.py"):
        # 将文件路径转换为模块路径
        relative_path = os.path.relpath(module_path, os.path.dirname(__file__))
        module_name = relative_path.replace(os.path.sep, ".").replace(".py", "")
        module = import_module(module_name)
        if hasattr(module, "router"):
            app.include_router(module.router)

# if __name__ == "__main__":
#     import uvicorn
#
#     uvicorn.run(app, host="127.0.0.1", port=8000, reload=True)


if __name__ == "__main__":
    os.system("uvicorn main:app --host 127.0.0.1 --port 8000 --reload")
    # 文档地址
    print('http://127.0.0.1:8000/docs')

